package by.gravity.drive_track.fragments;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import by.gravity.common.cache.db.ModelCacheManager;
import by.gravity.common.fragment.CommonDialogFragment;
import by.gravity.drive_track.AppIntents;
import by.gravity.drive_track.R;
import by.gravity.drive_track.adapter.FavoriteAdapter;
import by.gravity.drive_track.model.Favorite;
import by.gravity.drive_track.ui.listView.SwipeDismissListViewTouchListener;

public class FavoritePointFragment extends CommonDialogFragment implements AppIntents {

	public static final String TAG = FavoritePointFragment.class.getSimpleName();

	private FavoriteAdapter mAdapter;

	private ModelCacheManager mCacheManager;

	private ListView mListView;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mListView = (ListView) getView().findViewById(R.id.list);
		mCacheManager = ModelCacheManager.get(getActivity());
		List<Favorite> favoriteList = new ArrayList<Favorite>();
		mAdapter = new FavoriteAdapter(getActivity(), R.layout.favorite_item, favoriteList);
		List<Favorite> dbFavorite = (List<Favorite>) mCacheManager.getModelList(Favorite.class);
		if (dbFavorite != null) {
			favoriteList.addAll(dbFavorite);
			mAdapter.notifyDataSetChanged();
		}
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> paramAdapterView, View paramView, int paramInt, long paramLong) {
				Intent intent = new Intent(ADD_POINT_NAME_FROM_FAVORITE_INTENT);
				intent.putExtra(ARG_FAVORITE_POINT, mAdapter.getItem(paramInt));
				sendBroadcast(intent);
				dismiss();
			}
		});
		
		
		SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(mListView,
				new SwipeDismissListViewTouchListener.OnDismissCallback() {
					@Override
					public void onDismiss(ListView listView, int[] reverseSortedPositions) {
						for (int position : reverseSortedPositions) {
							mCacheManager.deleteModel(mAdapter.getItem(position));
							mAdapter.remove(mAdapter.getItem(position));
						}
						mAdapter.notifyDataSetChanged();
						
					}
				});
		mListView.setOnTouchListener(touchListener);
		mListView.setOnScrollListener(touchListener.makeScrollListener());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		getDialog().setTitle(R.string.favorited_points);
		return inflater.inflate(R.layout.list, null);
	}

}
